﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Joyeon.Utils
{
    /// <summary>
    /// 读取和写入配置文件key-value键值对
    /// </summary>
    public static class ApplicationSettingUtil
    {
        private static Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        /// <summary>
        /// 保存一个key的value值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private static void Save(String key, String value)
        {
            //Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings[key].Value = value;
            config.Save();
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 获得指定key的value
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static String GetValue(String key) 
        {
            String value = null;
            if (key!=null)
            {
                value = ConfigurationManager.AppSettings[key];
            }
            return value;
        }

        /// <summary>
        /// 向配置文件写入指定的key和value值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private static void AddKey(String key, String value) 
        {
            if (!IsKeyExist(key))
            {
                config.AppSettings.Settings.Add(key, value);
                config.Save();
                ConfigurationManager.RefreshSection("appSettings");
            }            
        }

        /// <summary>
        /// 检查一个key是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static bool IsKeyExist(String key) 
        {
            return config.AppSettings.Settings[key] == null;
        }
    }
}
